package com.ruoyi.user.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class WxJwtUtils {
    // 从配置读取（与系统端隔离）
    private String wxSecretKey;
    private long wxExpiration;
    
    @Value("${wx.jwt.secret}")
    public void setWxSecretKey(String secret) {
        this.wxSecretKey = secret;
    }

    @Value("${wx.jwt.expiration}")
    public void setWxExpiration(long expiration) {
        this.wxExpiration = expiration;
    }

    // 生成微信专用Token
    public String generateWxToken(String openId) {
        if (wxSecretKey == null) {
            throw new IllegalStateException("微信JWT密钥未配置，请检查wx.jwt.secret配置项");
        }
        return Jwts.builder()
                .setSubject("WX_" + openId) // 添加标识前缀
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + wxExpiration))
                .signWith(SignatureAlgorithm.HS512, wxSecretKey)
                .compact();
    }

    // 解析微信Token
    public String parseWxToken(String token) {
        if (wxSecretKey == null) {
            throw new IllegalStateException("微信JWT密钥未配置，请检查wx.jwt.secret配置项");
        }
        Claims claims = Jwts.parser()
                .setSigningKey(wxSecretKey)
                .parseClaimsJws(token)
                .getBody();

        if (!claims.getSubject().startsWith("WX_")) {
            throw new JwtException("非微信Token");
        }
        return claims.getSubject().substring(3); // 返回原始openId
    }
}